package demon1;

import java.util.Arrays;

public class MyArrayList implements IList{
    public int useSize;
    public int[]elem=new int[10];
    public boolean isFull(){
        if(this.useSize==this.elem.length){
            return true;
        }
        return false;
    }
    public void Expansion(){
        this.elem=Arrays.copyOf(this.elem,this.elem.length*2);
    }
    private void checkPos(int pos)throws PosNotLegalException{
        if(pos<0||pos>useSize){
            throw new PosNotLegalException("pos位置不合法");
        }

    }
    @Override
    public void add(int data) {
        if(isFull()){
            Expansion();
        }
        this.elem[useSize]=data;
        useSize++;
    }

    @Override
    public void add(int pos, int data) {
        if(isFull()){
            Expansion();
        }
        //判断pos位置的合法性.
        try{
            checkPos(pos);
        }catch (PosNotLegalException e){
            e.printStackTrace();
        }
        for (int i = this.useSize-1; i <=pos ; i--) {
            this.elem[i+1]=this.elem[i];
        }
        this.elem[pos]=data;
        useSize++;
    }
    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if(this.elem[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if(this.elem[i]==toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        try{
            checkPos(pos);
        }catch (PosNotLegalException e){
            e.printStackTrace();
        }
        return this.elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        if(isFull()){
            Expansion();
        }
        try{
            checkPos(pos);
        }catch (PosNotLegalException e){
            e.printStackTrace();
        }
        this.elem[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        int pos=indexOf(toRemove);
        if(pos==-1){
            return;
        }
        for (int i = pos; i < useSize-1; i++) {
            this.elem[i]=this.elem[i+1];
        }
        useSize--;
    }

    @Override
    public int size() {
        return useSize;
    }

    @Override
    public void clear() {
        useSize=0;
    }

    @Override
    public void display() {
        for (int i = 0; i < this.useSize; i++) {
            System.out.println(i);
        }
    }
}
